
import Link from './link'
import Task from './task'
import Marker from './marker'
class GantEvent {
  constructor ({ inlineEdit, gantt, vue, VueGantt }) {
    this.inlineEdit = inlineEdit // 内联编辑
    this.gantt = gantt
    this.vue = vue
    this.VueGantt = VueGantt
    this.marker = new Marker({ gantt: this.gantt })
    this.flag = true
  }

  registerEditEvent () {
    this.allowDialogEdit()
    this.taskClick()
    this.gantt.attachEvent('onTaskOpened', function (id) {
      console.log(id, 'a')
    })
    this.handleMarkDataEvent()
  }

  taskClick () {
    this.gantt.attachEvent('onTaskClick', (id, e) => {
      const target = this.VueGantt.task.data.find(v => `${v.id}` === `${id}`)
      if (target && e.target.className.includes('gantt_task_content')) {
        const status = target.open
        status ? this.gantt.close(id) : this.gantt.open(id)
        target.open = !target.open
      }
      if (e.target.className === 'checkboxCls') {
        const id = e.target.id
        const target = this.VueGantt.task.data.find(v => `${v.id}` === `${id}`)
        if (target) {
          console.log(target, 'target', !target.checked)
          this.vue.$set(target, 'checked', !target.checked)
        }
      }
      this.vue.$emit('onTaskClick', { id, e })
      return true
    })
  }

  handleMarkDataEvent () {
    window.addEventListener('click', (e) => {
      if (e.target.className.indexOf('gantt_marker') > -1) {
        const markerId = e.target.dataset.markerId
        const data = this.marker.getMarkData(markerId)
        this.vue.$emit('gantMarkerClick', data)
      } else if (e.target.className.indexOf('caret') > -1) { // 表头点击收缩
        const targetId = this.VueGantt.task.data.map(v => v.id)
        for (let i = 0; i < targetId.length; i++) {
          const v = targetId[i]
          this.flag ? this.gantt.open(v) : this.gantt.close(v)
        }
        this.flag = !this.flag
      } else if (e.target.className.indexOf('gantt_grid_resize_wrap') > -1) { // 切换侧边栏
        this.vue.setGridWidth()
      } else {
        this.vue.$emit('gantMarkerClick', {})
      }
    })
  }

  allowDialogEdit () { // 不允许弹窗编辑
    this.gantt.attachEvent(
      'onBeforeLightbox',
      (id) => {
        return false // 返回 false
      },
      {}
    )
  }

  init () {
    const link = new Link({ gantt: this.gantt, vue: this.vue, VueGantt: this.VueGantt })
    const task = new Task({ gantt: this.gantt, vue: this.vue, VueGantt: this.VueGantt })

    link.init()
    task.init()
    this.registerEditEvent()
  }
}
export default GantEvent
